package com.cloud.item.client.isolation;

import com.netflix.hystrix.*;
import feign.Feign;
import feign.Target;
import feign.hystrix.SetterFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;

/**
 * @author lscl
 * @version 1.0
 * @intro: 调用Order服务的线程池隔离配置
 */
@Configuration
public class OrderSemaphoreIsolationConfig {
    @Bean
    public SetterFactory setterFactory() {
        SetterFactory setterFactory = new SetterFactory() {
            @Override
            public HystrixCommand.Setter create(Target<?> target, Method method) {

                // 服务分组名称
                String groupKey = target.name();

                // 接口名称
                String commandKey = Feign.configKey(target.type(), method);

                // Hystrix配置
                HystrixCommandProperties.Setter commandProp = HystrixCommandProperties.Setter()
                        // 设置信号量隔离
                        .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
                        .withExecutionIsolationSemaphoreMaxConcurrentRequests(3);

                return HystrixCommand.Setter
                        .withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
                        .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey))
                        .andCommandPropertiesDefaults(commandProp);
            }
        };
        return setterFactory;
    }

}

